package com.cola.dao;

import com.cola.utils.DateUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.*;

/**
 * Created by Max on 2017/8/17.
 */
public class BaseDao {
    private final Logger logger = LoggerFactory.getLogger(getClass());

    private QueryRunner queryRunner = null;
    public QueryRunner getQueryRunner(){
        if (null == queryRunner) {
            queryRunner = new QueryRunner();
        }
        return queryRunner;
    }

    /**
     * 拼接update sql语句
     */
    public Map<String, Object> getUpdateSql(Map<String, Object> map) {
        Iterator entries = map.entrySet().iterator();
        StringBuilder sql = new StringBuilder();
        Map<String, Object> sqlMap = new HashMap();
        List<Object> params = new ArrayList();
        while (entries.hasNext()) {
            Map.Entry entry = (Map.Entry) entries.next();
            if ("task_id".equals((String) entry.getKey())) {
                continue;
            }
            sql.append((String) entry.getKey() + " =? ,");

            if ("task_name".equals((String) entry.getKey())
                    || "red_packet_config".equals((String) entry.getKey())
                    || "advanced_condition_config".equals((String) entry.getKey())
                    || "task_start_time".equals((String) entry.getKey())
                    || "task_end_time".equals((String) entry.getKey())) {
                params.add((String) entry.getValue());
            } else {
                params.add((Integer) entry.getValue());
            }

        }
        params.add(map.get("task_id").toString());
        sqlMap.put("sql", sql.toString());
        sqlMap.put("params", params);
        return sqlMap;
    }
    /**
     * 解析RS结果集
     * @param rs rs结果集
     * @param reMap 结果集
     */
    protected void parseRs(ResultSet rs, Map reMap) throws SQLException {
        if (null!=rs){
            ResultSetMetaData rsmd = rs.getMetaData();
            if (null!=rsmd){
                String[] columnNames = new String[rsmd.getColumnCount()];
                for(int i = 0;i < rsmd.getColumnCount();i++){
                    columnNames[i] = rsmd.getColumnName(i + 1);
                }
                while (rs.next()){
                    for(String column: columnNames){
                        Object object = rs.getObject(column);
                        putObject(reMap,column,object);
                    }
                }
            }
        }
    }

    /**
     * 解析RS结果集
     * @param rs rs结果集
     * @param reList 结果集
     */
    protected void parseRs(ResultSet rs, List<Map<String,Object>> reList) throws SQLException {
        Map reMap ;
        if (null!=rs){
            ResultSetMetaData rsmd = rs.getMetaData();
            if (null!=rsmd){
                String[] columnNames = new String[rsmd.getColumnCount()];
                for(int i = 0;i < rsmd.getColumnCount();i++){
                    columnNames[i] = rsmd.getColumnName(i + 1);
                }
                while (rs.next()){
                    reMap = new HashMap<String,Object>();
                    for(String column: columnNames){
                        Object object = rs.getObject(column);
                        putObject(reMap,column,object);
                    }
                    reList.add(reMap);
                }
            }
        }
    }


    protected void putObject(Map map,String key,Object object){
        if (object instanceof String){
            map.put(key,object+"");
        }else if (object instanceof Integer){
            map.put(key,Integer.valueOf(object+""));
        }else if (object instanceof Long ){
            map.put(key,Long.valueOf(object+""));
        }else if (object instanceof Date){
            map.put(key, DateUtils.formatTime((Date) object));
        }else{
            map.put(key,object);
        }
    }

    /**
     * 连接提交
     * @param conn
     */
    protected void connCommit(Connection conn){
        try {
            conn.commit();
        } catch (Exception e) {
            logger.error("",e);
        }
    }

    /**
     * 连接回滚
     * @param conn
     */
    protected void connRollback(Connection conn){
        try {
            conn.rollback();
        } catch (Exception e) {
            logger.error("",e);
        }
    }

    protected void connReset(Connection conn){
        try {
            conn.setAutoCommit(true);
        } catch (Exception e) {
            logger.error("",e);
        }
    }
}
